package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.AdviceMapper;
import com.itheima.pojo.Advice;
import com.itheima.pojo.Exercise;
import com.itheima.pojo.Food;
import com.itheima.service.AdviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = AdviceService.class)
@Transactional
public class AdviceServiceImpl implements AdviceService {


    @Autowired
    private AdviceMapper adviceMapper;

    //添加健康建议
    @Override
    public void add(Integer[] foodIds, Integer[] exerciseIds, Advice advice) {
        //1.先向数据库中添加建议信息,再获取添加后返回的id
        adviceMapper.add(advice);
        Integer adviceId = advice.getId();
        //遍历运动数组和膳食数组,向关联表中添加关联
        Map map = new HashMap<Integer, Integer>();
        for (Integer foodId : foodIds) {
            map.put("foodId",foodId);
            map.put("adviceId",adviceId);
            adviceMapper.addFoodId(map);
        }

        //遍历运动数组,向关联表中添加运动数据
        for (Integer exerciseId : exerciseIds) {
            map.put("exerciseId",exerciseId);
            map.put("adviceId",adviceId);
            adviceMapper.addExerciseId(map);
        }
    }



    //根据订单id查询健康干预
    @Override
    public Advice findById(Integer order_id) {
        return adviceMapper.findById(order_id);
    }

    //根据订单id查询对应健康建议的所有运动信息
    @Override
    public List<Integer> findExerciseById(Integer order_id) {

        return adviceMapper.findExerciseById(order_id);
    }

    //根据订单id查询对应健康建议的所有膳食信息
    @Override
    public List<Integer> findFoodById(Integer order_id) {
        return adviceMapper.findFoodById(order_id);
    }

    @Override
    public void edit(Integer[] foodIds, Integer[] exerciseIds, Advice advice) {
        Integer order_id = advice.getOrder_id();
        Advice adviceTem = adviceMapper.findById(order_id);
        //将根据订单id查询后的健康建议 赋值订单给前端传入的健康建议id
        advice.setId(adviceTem.getId());

        //1.先向数据库中修改建议信息
        adviceMapper.edit(advice);
        Integer adviceId = advice.getId();
        //2.删除关联表中该建议 原有的关联数据
        adviceMapper.deleteById4Food(adviceId);
        adviceMapper.deleteById4Exercise(adviceId);

        //3.遍历运动数组和膳食数组,向关联表中再添加关联
        Map map = new HashMap<Integer, Integer>();
        for (Integer foodId : foodIds) {
            map.put("foodId",foodId);
            map.put("adviceId",adviceId);
            adviceMapper.addFoodId(map);
        }
        //遍历运动数组,向关联表中添加运动数据
        for (Integer exerciseId : exerciseIds) {
            map.put("exerciseId",exerciseId);
            map.put("adviceId",adviceId);
            adviceMapper.addExerciseId(map);
        }
    }
}
